<template>
  <el-dialog
    title="定制视频封面"
    :visible.sync="coversShow"
    :modal-append-to-body="false"
    :append-to-body="false"
    :modal="false"
    @close="closeCover"
  >
    <div v-loading="fetchDataLoading">
      <div style="margin: 5px">请在下方选择视频</div>
      <div style="text-align: right; margin: 5px;">
        <input
          type="file"
          ref="file"
          hidden
          @change="onFileChange"
        >
        <el-button type="text" @click="$refs.file.click()">
          <i class="el-icon-plus"></i>上传
        </el-button>
        <!--<el-button type="text" @click="addNewCoverShow = true">-->
        <!--  <i class="el-icon-plus"></i>旧上传-->
        <!--</el-button>-->
      </div>
      <div class="infinite-list-wrapper" style="overflow:auto;max-height: 500px">
        <el-row :gutter="20" v-loading="loading">
          <el-col v-for="(item, idx) in covers" :span="6">
            <el-radio v-model="choose" :label="idx" style="margin: 5px" :id="'radio'+idx">封面{{idx + 1}}</el-radio>
            <el-image :src="item.ttCoverUrl" style="width: 180px;height: 320px;cursor: pointer" @click="chooseCover(idx)"></el-image>
          </el-col>
        </el-row>
      </div>
      <div style="margin: 10px;text-align: right">
        <el-button type="primary" @click="saveSuggestCover" v-loading="btnLoading">保存</el-button>
        <el-button @click="closeCover">取消</el-button>
      </div>
      <div>
        <update-photo v-if="isUpdatePhotoShow" :visible.sync="isUpdatePhotoShow" :img="img" @upload="uploadImg"></update-photo>
        <el-dialog
          title="上传自定义封面"
          :visible.sync="addNewCoverShow"
          :close-on-click-modal="false"
          :modal-append-to-body="false"
          :modal="false"
          width="600px"
          @close="closeNewCoverUploader"
        >
          <div style="text-align: center">
            <el-form v-model="newCoverForm" ref="newCoverForm">
              <el-form-item>
                <el-upload
                  action="#"
                  :http-request="uploadQiniuCloud"
                  :before-upload="beforeCoverUpload"
                  :limit="1"
                  list-type="picture">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
                <!--                <el-image v-if="newCoverForm.creativeUrl !==''"-->
                <!--                          :src="newCoverForm.creativeUrl"-->
                <!--                          style="width: 180px;height: 320px;"></el-image>-->
              </el-form-item>
              <el-form-item>
                <div style="color: red">
                  <p>图片尺寸推荐: 长/宽：1200*628 像素、375*604 像素、640*640 像素或 720*1280 像素
                  <p>文件格式：.jpg、.jpeg 或 .png</p>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div style="margin: 10px;text-align: center">
            <el-button type="primary" @click="saveNewCover" v-loading="uploadBtnLoading">上传封面</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </el-dialog>
</template>
<div>

</div>
<script>
import {getSuggestCover, uploadTtCover} from "@/api/campaign-management/campaign-management";
import * as qiniuTools from "@/util/qinnu_upload";
import _ from "lodash";
import UpdatePhoto
  from "@/views/campaign-management/components/UpdatePhoto";

export default {
  name: "SuggestCover",
  props: {
    creative: {
      type: Object,
    },
    accountId: {
      type: String
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    UpdatePhoto
  },
  computed: {
    coversShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
    // this.fakeData()
    this.getSuggestCoverData()
  },
  data() {
    return {
      covers: [],
      choose: '',
      coverId: '',
      fetchDataLoading: false,
      addNewCoverShow: false,
      newCoverForm: {},
      creativeUrl: '',
      btnLoading: false,
      uploadBtnLoading: false,
      img: null,
      isUpdatePhotoShow: false,
      loading: false
    }
  },
  methods: {
    fakeData() {
      let cvs = [
        {ttCoverUrl: "http://image-origin-bucket.ninesword.com/8363736654520.jpg"},
        {ttCoverUrl: "http://image-origin-bucket.ninesword.com/5325358230399.jpg"},
        {ttCoverUrl: "http://image-origin-bucket.ninesword.com/2185314712701.jpg"},
        {ttCoverUrl: "http://image-origin-bucket.ninesword.com/5829670356728.jpg"},
        {ttCoverUrl: "http://image-origin-bucket.ninesword.com/5829670356728.jpg"},
        {ttCoverUrl: "http://image-origin-bucket.ninesword.com/5829670356728.jpg"},
        {ttCoverUrl: "http://image-origin-bucket.ninesword.com/5829670356728.jpg"},
        {ttCoverUrl: "http://image-origin-bucket.ninesword.com/5829670356728.jpg"},
        {ttCoverUrl: "http://image-origin-bucket.ninesword.com/5829670356728.jpg"},
        {ttCoverUrl: "http://image-origin-bucket.ninesword.com/5829670356728.jpg"},
      ]
      this.covers = cvs
    },
    getSuggestCoverData() {
      this.fetchDataLoading = true
      getSuggestCover(this.accountId, this.creative.id).then(res => {
        this.covers = res.data.data
      })
        .catch(err => {
          this.$message.error(err)
          this.closeCover()
        })
        .finally(() => {
          this.fetchDataLoading = false
        })
    },
    saveSuggestCover() {
      this.btnLoading = true
      this.coverId = this.covers[parseInt(this.choose)].coverImgId
      let url = _.cloneDeep(this.covers[parseInt(this.choose)].ttCoverUrl)
      this.$emit("returnCoverId",
        this.coverId, _.cloneDeep(this.creative.id), _.cloneDeep(this.accountId), url)
      this.closeCover()
    },
    beforeCoverUpload(file) {
      var img = file.name.substring(file.name.lastIndexOf('.') + 1)
      const suffix = img.toLowerCase() === 'jpg'
      const suffix2 = img.toLowerCase() === 'png'
      const suffix3 = img.toLowerCase() === 'jpeg'
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!suffix && !suffix2 && !suffix3) {
        this.$message.error("只能上传图片！");
        return false
      }
      // 可以限制图片的大小
      // if (!isLt1M) {
      //   this.$message.error('上传图片大小不能超过 1MB!');
      // }
      return suffix || suffix2 || suffix3
    },
    uploadCover() {
    },
    closeCover() {
      this.coversShow = false
    },
    uploadQiniuCloud(file) {
      console.log('上传',file)
      const that = this
      const fileData = qiniuTools.getFileData(file)
      const callback = {
        next(res) {
        },
        error(err) {
          this.$message.error("上传图片失败! err => " + err);
        },
        complete(res) {
          const url = 'http://' + fileData.server + '/' + res.key
          that.$set(that, 'creativeUrl', url)
          // that.logoUrl = url
        }
      }
      const uploader = qiniuTools.uploadQiniuCloud(file, fileData)
      uploader.subscribe(callback)
    },
    saveNewCover() {
      this.uploadBtnLoading = true
      let params = {
        accountId: this.accountId,
        creativeId: this.creative.id,
        creativeName: this.creative.name,
        creativeUrl: this.creativeUrl
      }
      uploadTtCover(params).then(res => {
        this.covers.push(res.data.data)
        this.choose = this.covers.length.toString()
        this.$message.success("上传封面成功")
      }).finally(() => {
        this.closeNewCoverUploader()
      })
    },
    closeNewCoverUploader() {
      this.addNewCoverShow = false
      this.creativeUrl = ''
      this.uploadBtnLoading = false
    },
    onFileChange() {
      // 获取文件对象
      const file = this.$refs.file.files[0]
      // 基于文章对象获取 blob 数据
      this.img = window.URL.createObjectURL(file)

      // 展示预览图片弹出层
      this.isUpdatePhotoShow = true

      // file-input 如果选了同一个文件不会触发 change 事件
      // 解决办法就是每次使用完毕，把它的 value 清空
      this.$refs.file.value = ''
    },
    uploadImg(url) {
      let params = {
        accountId: this.accountId,
        creativeId: this.creative.id,
        creativeName: this.creative.name,
        creativeUrl: url
      }
      this.loading = true
      uploadTtCover(params).then(res => {
        this.covers.push(res.data.data)
        // this.choose = this.covers.length.toString()
      }).finally(()=>{
        this.loading = false
      })
    },
    chooseCover(idx) {
      this.choose = idx
    }
  }
}
</script>
